<template>
  <div style="width: 50%">
    <div class="card" style="padding: 30px">
      <el-form :model="user" label-width="100px" style="padding-right: 50px">
        <el-form-item label="头像">
          <el-upload class="avatar-uploader" :action="`${baseUrl}/image/upload`" :show-file-list="false"
            :on-success="handleAvatarSuccess">
            <img v-if="user.avatar" :src="`${baseUrl}/image/download/${user.avatar}`" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="账号">
          <el-input disabled v-model="user.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="user.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="user.gender">
            <el-radio label="男" value="男">男</el-radio>
            <el-radio label="女" value="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input-number v-model="user.age" :min="1" :max="120" controls-position="right" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="user.phone" placeholder="请输入手机号" maxlength="11" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="user.email" placeholder="请输入邮箱地址" />
        </el-form-item>
        <div style="text-align: center">
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { updateUser } from "@/api/user";
export default {
  data() {
    return {
      user: {},
      baseUrl: process.env.VUE_APP_BASE_URL,
    };
  },
  created() {
    this.user = this.$store.getters.user
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.user.avatar = res;
    },
    async handleSave() {
      const res = await updateUser(this.user)
      if (res.code === 200) {
        this.$message.success('修改成功');
        this.$store.commit("SET_USER", this.user)
      } else {
        this.$message.error(res.message || '修改失败');
      }
    },
  },
};
</script>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>